import importlib
import inspect
import os
from pathlib import Path
import sys
from PluginBase import PluginBase

class PluginManager:
    def __init__(self):
        self.tools = {}
        self.functions = {}
 
    def load_plugins(self, plugin_dir="plugins"): 
        current_dir = os.path.dirname(os.path.abspath(__file__))
        # 构造 plugin 子目录的绝对路径
        plugin_dir = os.path.join(current_dir, "plugins") 
        sys.path.insert(0, plugin_dir) 

        # 动态加载插件目录
        plugins_path = Path(plugin_dir)
        print(f"加载插件目录 {plugins_path}")
        for file in plugins_path.glob("Plugin_*.py"): 
            if  False == file.name.startswith("Plugin_"):
                continue
             
            module_name = file.stem
            try: 
                mName=f"{module_name}"
                module = importlib.import_module(mName)
                for name, cls in inspect.getmembers(module, self._is_plugin_class):
                    self._register_plugin(cls)
            except Exception as e:
                print(f"加载插件 {module_name} 失败: {str(e)}")
    
    def _is_plugin_class(self, obj):
        return inspect.isclass(obj) and issubclass(obj, PluginBase) and obj != PluginBase
    
    def _register_plugin(self, pluginClass):
        pluginInstance = pluginClass()
        self.tools.update(pluginInstance.get_tools())
        self.functions.update(pluginInstance.get_functions())